<?php
namespace Admin\Model;

use Admin\Model\BaseModel;

class AdModel extends BaseModel{
    protected $_validate = array(
        //array(验证字段1,验证规则,错误提示,[验证条件,附加规则,验证时间]),
        array('ad_name','require','广告名称必须填写',1,'',3),
        array('ad_name','1,30','广告名称必须是在1-30个字符之间', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
        array('ad_link','require','广告链接必须填写',1,'',3),
        array('ad_link','1,100','广告链接必须是在1-100个字符之间', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
        array('pic_id','is_numeric','请正确的上传图片',1,'function',3),
        array('sort','is_numeric','排序只能为数字',1,'function',3),
    );
    
    protected $_auto = array(
        //array(完成字段1,完成规则,[完成条件,附加规则]),
        array('status','1',1),
        array('create_time',NOW_TIME,1),
        array('update_time',NOW_TIME,3)
    );
    
    /**
     * @todo 返回主键
     * @see \Think\Model::getPk()
     */
    public function getPk(){
        return 'ad_id';
    }
    
    /**
     * @todo 修改广告所属位置
     * @param ing $ad_id 广告id
     * @param array $ad_position_id 位置id
     */
    function updateAdPosition($ad_id,$ad_position_id){
        $ad_id = (int)$ad_id;
        $ad_position_id = empty($ad_position_id) ? array() : (array)$ad_position_id;
        if($ad_id == 0){
            $this->error = '广告id错误';
            return false;
        }
        if(empty($ad_position_id)){
            $this->error = '没有选择广告位置';
            return false;
        }
        
        $data = array();
        foreach ($ad_position_id as $val){
            $data[] = array(
                'ad_id'=>$ad_id,
                'ad_position_id'=>$val
            );
        }
        $ad_position_ad = M('ad_position_ad');
        if(!empty($data)){
            $ad_position_ad->where(array('ad_id'=>$ad_id))->delete();
            $ad_position_ad->addAll($data);
        }
        return true;
    }
}